package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/patient")
public class PatientController {

    @Autowired
    private UserService userService;

    // ✅ 分页获取全部患者
    @GetMapping
    public IPage<User> listAllPatients(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {

        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("user_type", 3); // 只查患者

        return userService.page(new Page<>(page, size), query);
    }

    // ✅ 模糊查询患者姓名
    @GetMapping("/search")
    public IPage<User> searchPatients(
            @RequestParam("name") String name,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "5") int size) {

        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("user_type", 3)
                .like("real_name", name);

        return userService.page(new Page<>(page, size), query);
    }

    // ✅ 更新患者信息
    @PostMapping("/update")
    public boolean updatePatient(@RequestBody User user) {
        user.setUserType(3); // 保证是患者类型
        return userService.updateById(user);
    }

    // ✅ 删除患者
    @DeleteMapping("/delete/{id}")
    public boolean deletePatientById(@PathVariable Integer id) {
        return userService.removeById(id);
    }

    // ✅ 新增患者
    @PostMapping("/add")
    public boolean addPatient(@RequestBody User user) {
        user.setUserType(3); // 必须设定为患者类型
        return userService.save(user);
    }

    // ✅ 更新患者状态
    @PostMapping("/updateStatus")
    public boolean updateStatus(@RequestBody User user) {
        if (user.getId() == null || user.getStatus() == null) return false;

        User update = new User();
        update.setId(user.getId());
        update.setStatus(user.getStatus());

        return userService.updateById(update);
    }
}
